package com.szosen.jkzj.activity.mbgy;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;

import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.szosen.application.MyApplication;
import com.szosen.database.DBService;
import com.szosen.database.VisitPlan;
import com.szosen.jkzj.R;
import com.szosen.jkzj.activity.BaseActivity;
import com.szosen.jkzj.activity.OfflineUploadListActivity;
import com.szosen.jkzj.activity.mbgy.plan.GXYPlan_Activity;
import com.szosen.web.WebService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class GXYPlanList extends BaseActivity {
	List<Data> datas;
	List<String[]> adapterList;
	DataAdapter mAdapter;
	// 刷新列表的标记
	private static final int WHAT_FRESHLIST = 0x32;
	ListView lv_userlist;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mbgy_plan_userlist);
		super.setTitleContent("【高血压随访计划】");
		initView();
	}

	@Override
	protected void onStart() {
		super.onStart();
		refreshData(null);
	}

	private void initView() {
		datas = new ArrayList<Data>();
		adapterList = new ArrayList<String[]>();
		lv_userlist = (ListView) findViewById(R.id.mbgy_plan_lv_userlist);
		et_PageIndex = (EditText) findViewById(R.id.mbgy_plan_userlist_et_pageIndex);
		et_PageCount = (EditText) findViewById(R.id.mbgy_plan_userlist_et_pageCount);
		mAdapter = new DataAdapter(context, adapterList);
		lv_userlist.setAdapter(mAdapter);
		lv_userlist.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				DataAdapter adapter = (DataAdapter) parent.getAdapter();
				String[] itemData = (String[]) adapter.getItem(position);
				String dataJsonStr = itemData[6];
				Intent intent = new Intent(GXYPlanList.this,
						GXYPlan_Activity.class);
				intent.putExtra("json", dataJsonStr);
				startActivity(intent);
			}
		});
	}

	Handler mUIHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case WHAT_FRESHLIST:
				mAdapter.notifyDataSetChanged();
				dismissDialog();
				break;

			default:
				break;
			}
		};
	};
	EditText et_PageIndex;
	EditText et_PageCount;
	int pageIndex = 1;

	/***
	 * 刷新数据
	 *
	 * @param view
	 */
	public void refreshData(View view) {
		checkPageEditText();
		int pageIndex_et = getIntByStr(getTextByEt(et_PageIndex));
		pageIndex = pageIndex_et;
		int pageCount = getIntByStr(getTextByEt(et_PageCount));
		if (!MyApplication.isConnected()) {
			// ToastTool.showLong(context, "当前无网络或未登录，请检查后再试！");
			// 网络无连接
			getDataFromLocal(pageIndex, pageCount);
		} else {
			getDataFromWeb(pageIndex, pageCount);
		}
	}

	AlertDialog mDialog = null;

	private void showDialog() {
		mDialog = showDialog("提示", "正在刷新数据，请稍候！", true);
		mDialog.show();
	}

	private void dismissDialog() {
		if (mDialog != null && mDialog.isShowing()) {
			mDialog.cancel();
		}
	}

	public void nextPage(View view) {
		checkPageEditText();
		int pageIndex_et = getIntByStr(getTextByEt(et_PageIndex));
		pageIndex = pageIndex_et + 1;
		et_PageIndex.setText(pageIndex + "");
		int pageCount = getIntByStr(getTextByEt(et_PageCount));
		if (!MyApplication.isConnected()) {
			// ToastTool.showLong(context, "当前无网络或未登录，请检查后再试！");
			// 网络无连接
			getDataFromLocal(pageIndex, pageCount);
		} else {
			getDataFromWeb(pageIndex, pageCount);
		}
	}

	private int getIntByStr(String str) {
		if (TextUtils.isEmpty(str)) {
			return 1;
		}
		int result = 1;
		try {
			result = Integer.parseInt(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/***
	 * 检查page的页码和页数。如果为空，就设置为默认值
	 */
	private void checkPageEditText() {
		String temp1 = getTextByEt(et_PageIndex);
		String temp2 = getTextByEt(et_PageCount);
		if (TextUtils.isEmpty(temp1)) {
			et_PageIndex.setText("1");
		}
		if (TextUtils.isEmpty(temp2)) {
			et_PageCount.setText("20");
		}
	}

	/***
	 * 跳转到离线记录的列表
	 *
	 * @param view
	 */
	public void goToOfflineList(View view) {
		Intent intent = new Intent(GXYPlanList.this,
				OfflineUploadListActivity.class);
		intent.putExtra(BaseActivity.ACTIVITY_FLAG,
				BaseActivity.ACTIVITY_FLAG_MBGY);
		startActivity(intent);
	}

	int queryType = 1;

	/***
	 * 从网络获取数据
	 */
	public void getDataFromWeb(int pageIndex, int pageCount) {
		showDialog();
		// 查询类型。1高血压，2糖尿病
		queryType = 1;
		WebService.queryVisitPlans(context, pageIndex, pageCount, "",
				new StringCallback() {
					@Override
					public void onSuccess(String str, Call call,
							Response response) {
						int middle = str.length() / 2;
						// System.out.println("返回的随访列表查询1：" +
						// str.substring(0,middle));
						// System.out.println("返回的随访列表查询2：" +
						// str.substring(middle,str.length()));
						JSONObject obj;
						try {
							obj = new JSONObject(str);
							JSONArray dataArray = obj.optJSONArray("data");
							if (dataArray != null) {
								datas.clear();
								adapterList.clear();
								for (int i = 0; i < dataArray.length(); i++) {

									String temp = dataArray.get(i).toString();
									Data data = new Gson().fromJson(temp,
											Data.class);
									String name = data.getPersonName();
									String sex = TextUtils.isEmpty(data
											.getSexCode()) ? "" : "1"
											.equals(data.getSexCode()) ? "男"
											: "女";
									String phone = data.getMobileNumber();
									String idcard = data.getIdCard();
									List<Plan> plans = data.getPlan();
									StringBuilder sb_type = new StringBuilder();
									StringBuilder sb_time = new StringBuilder();
									int gxy_or_tnb = 0;
									for (int j = 0; j < plans.size(); j++) {
										System.out.println("plans内容" + j + ":"
												+ plans.get(j));
										Plan p = plans.get(j);
										if (plans.size() > 1
												&& j < plans.size() - 1) {
											String businessType = p
													.getBusinessType();
											String type = ("1"
													.equals(businessType) ? "高血压"
													: "糖尿病");
											gxy_or_tnb = ("1"
													.equals(businessType) ? 1
													: 2);
											sb_type.append(type + "\n\n\n");
										} else {
											String businessType = p
													.getBusinessType();
											String type = ("1"
													.equals(businessType) ? "高血压"
													: "糖尿病");
											gxy_or_tnb = ("1"
													.equals(businessType) ? 1
													: 2);
											sb_type.append(type + "\n\n\n");
										}
										sb_time.append("计划日期:"
												+ p.getPlanDate() + "\n最早执行日期:"
												+ p.getBeginDate()
												+ "\n最晚执行日期:" + p.getEndDate()
												+ "\n");
									}
									if (queryType == gxy_or_tnb) {
										String[] strs = new String[] { name,
												sex, phone, idcard,
												sb_time.toString(),
												sb_type.toString(), temp };
										datas.add(data);
										System.out.println("刷新的datas，add数据"
												+ strs);
										adapterList.add(strs);
										VisitPlan vp = new VisitPlan();
										vp.setJson(temp);
										vp.setIdcard(idcard);
										vp.setType("gxy");
										DBService.add(vp);
									}
								}
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						// 获取数据成功后刷新界面数据
						mUIHandler.obtainMessage(WHAT_FRESHLIST).sendToTarget();
					}
				});
	}

	/***
	 * 从网络获取数据
	 */
	public void getDataFromLocal(int pageIndex, int pageCount) {
		showDialog();
		// 查询类型。1高血压，2糖尿病
		queryType = 1;
		datas.clear();
		adapterList.clear();
		List<Object> vps = DBService.getAll(new VisitPlan());
		for (int i = 0; i < vps.size(); i++) {
			VisitPlan temp = (VisitPlan) vps.get(i);
			String jsonStr = temp.getJson();
			Data data = new Gson().fromJson(jsonStr, Data.class);
			String name = data.getPersonName();
			String sex = TextUtils.isEmpty(data.getSexCode()) ? "" : "1"
					.equals(data.getSexCode()) ? "男" : "女";
			String phone = data.getMobileNumber();
			String idcard = data.getIdCard();
			List<Plan> plans = data.getPlan();
			StringBuilder sb_type = new StringBuilder();
			StringBuilder sb_time = new StringBuilder();
			int gxy_or_tnb = 1;
			boolean hasgxy = false;
			for (int j = 0; j < plans.size(); j++) {
				System.out.println("plans内容" + j + ":" + plans.get(j));
				Plan p = plans.get(j);
				String businessType = p.getBusinessType().trim();
				String type = ("1".equals(businessType) ? "高血压" : "糖尿病");
				gxy_or_tnb = ("1".equals(businessType) ? 1 : 2);
				if (gxy_or_tnb == 1 && !hasgxy) {
					hasgxy = true;
					sb_type.append(type + "\n\n\n");
					sb_time.append("计划日期:" + p.getPlanDate() + "\n最早执行日期:"
							+ p.getBeginDate() + "\n最晚执行日期:" + p.getEndDate());
					gxy_or_tnb=0;
				}
			}
			if (queryType == gxy_or_tnb || hasgxy) {
				String[] strs = new String[] { name, sex, phone, idcard,
						sb_time.toString(), sb_type.toString(), jsonStr };
				datas.add(data);
				System.out.println("刷新的datas，add数据" + strs);
				adapterList.add(strs);
				hasgxy=false;
			}
		}
		// 获取数据成功后刷新界面数据
		mUIHandler.obtainMessage(WHAT_FRESHLIST).sendToTarget();
	}
}
